package com.zm.admin.listener;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zm.admin.utils.ServletUtil;
import com.zm.admin.zmeng.controller.LoginController;
import com.zm.admin.zmeng.domain.ZmVisitor;
import com.zm.admin.zmeng.mapper.ZmVisitorMapper;
import com.zm.admin.utils.AddressUtil;
import com.zm.admin.utils.UserIpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.annotation.Resource;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/***
 *
 * @Auther: MuYun
 * @Date: 2022/12/1 21:39
 * @Description： 访客监听类
 *
 */
@WebListener
public class VisitListener implements ServletRequestListener {

    private static Logger logger= LoggerFactory.getLogger(LoginController.class);

    @Resource
    private ZmVisitorMapper zmVisitorMapper;

    @Override
    public void requestInitialized(ServletRequestEvent event) {
        //logger.info("监听启动0.0");
        try{
            //获取当前进来的request请求
            WebApplicationContextUtils.getRequiredWebApplicationContext(event.getServletContext())
                    .getAutowireCapableBeanFactory().autowireBean(this);
            //获取当前进来的request请求
            HttpServletRequest request = (HttpServletRequest) event.getServletRequest();
            //获取session
            HttpSession session = request.getSession();
            ZmVisitor visitor=new ZmVisitor();
            if(session.isNew()){
                visitor.setCreateTime(DateUtil.date());
                String ip = UserIpUtil.getIp(request);
                String userAgentStr = request.getHeader("user-agent");
                //倒退12个小时
                LocalDateTime dateTime = LocalDateTime.now().minusHours(12);
                QueryWrapper<ZmVisitor> wrapper=new QueryWrapper<>();
                //logger.info("看看参数，ip：{},userAgent:{},datetime:{}",ip,userAgentStr,dateTime);
                wrapper.lambda().eq(ZmVisitor::getIp,ip);
                wrapper.lambda().eq(ZmVisitor::getUserAgent,userAgentStr);
                wrapper.lambda().ge(ZmVisitor::getCreateTime,dateTime);
                wrapper.lambda().le(ZmVisitor::getCreateTime,LocalDateTime.now());
                synchronized (this){
                    List<ZmVisitor> zmVisitors = zmVisitorMapper.selectList(wrapper);
                    //进一步解析
                    UserAgent userAgent = UserAgentUtil.parse(userAgentStr);
                    if(zmVisitors.size()==0){
                        visitor.setIp(ip);
                        visitor.setUserAgent(userAgentStr);
                        visitor.setBrowserType(userAgent.getBrowser().toString()+"  "+userAgent.getVersion());
                        visitor.setPlatformType(userAgent.getPlatform().toString());
                        visitor.setUrl(request.getRequestURL().toString());
                        //通过ip和编码获取ip对应地址
                        visitor.setCity(new AddressUtil().getAddresses("ip="+ip,"GBK"));
                        logger.info("当前访客:{}",visitor);
                        zmVisitorMapper.insert(visitor);
                    }
                }
            }
        }catch (Exception e){
            logger.error("访客监听报错了：{}",e);
        }
    }
}
